<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./../bootstrap/css/bootstrap.css">
  <style>
    #myPage {
      display: none;
    }

    .pagination,
    #page {
      float: left;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-12">
        <a href="./doctors.html">医生管理</a>
      </div>
      <div class="col">
        <h1 class="header">医生职称管理：</h1>
        <div class="my-5">
          <button class="btn btn-primary" type="button" id="addJobBtn">添加职称</button>
        </div>
        <div>
          <table class="table table-hover">
            <thead>
              <tr>
                <th>序号</th>
                <th>职称名称</th>
                <th>职称描述</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody id="jobTable">
              <tr>
                <td></td>
                <td></td>
                <td></td>
                <td>
                  <button type="button" class="btn btn-waring btn-edit">修改</button>
                  <button type="button" class="btn btn-danger btn-delete">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <!-- 分页 -->
        <div id="myPage">
          <nav>
            <ul class="pagination pagination-sm">
              <!-- <li class="page-item active" aria-current="page">
                <span class="page-link">1</span>
              </li>
              <li class="page-item"><a class="page-link" href="#">2</a></li>
              <li class="page-item"><a class="page-link" href="#">3</a></li> -->
            </ul>
            <select name="page" id="page">
              <!-- <option value="5">5</option> -->
            </select>
          </nav>
        </div>
      </div>
    </div>
  </div>
  <!-- 添加 -->
  <div class="modal" tabindex="-1" id="addJobModal">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">添加职称</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form>
            <div class="form-group">
              <label for="jobname">职称名称：</label>
              <input type="email" name="jobname" class="form-control" id="jobname" aria-describedby="emailHelp">
              <small id="jobnamehelp" class="form-text text-muted">请输入20字以内得职称名称</small>
            </div>
            <div class="form-group">
              <label for="jobdes">职称描述：</label>
              <input type="text" class="form-control" id="jobdes">
              <small id="jobdeshelp" class="form-text text-muted">请输入50字以内得职称描述</small>

            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary btn-add">添加</button>
        </div>
      </div>
    </div>
  </div>
  <!-- 修改 -->
  <div class="modal" tabindex="-1" id="editJobModal">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">修改职称</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form>
            <div>
              <input type="hidden" name="jid" id="jid" value="">
            </div>
            <div class="form-group">
              <label for="jobname2">职称名称：</label>
              <input type="email" name="jobname" class="form-control" id="jobname2" aria-describedby="emailHelp">
              <small id="jobnamehelp2" class="form-text text-muted">请输入20字以内得职称名称</small>
            </div>
            <div class="form-group">
              <label for="jobdes2">职称描述：</label>
              <input type="text" class="form-control" id="jobdes2">
              <small id="jobdeshelp2" class="form-text text-muted">请输入50字以内得职称描述</small>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary btn-edit">保存</button>
        </div>
      </div>
    </div>
  </div>
</body>
<script src="./../jquery/jquery 3.5.1.js"></script>
<script src="./../bootstrap/js/bootstrap.bundle.js"></script>
<script>
  window.onload = function () {
    // getJobsData();
    getJobsDataPage(nowpage, pagesize)
  };


  let nowpage = 1, pagesize = 5, pageSizes = [5, 10, 20, 50];
  let total = 0;// 总页数

  // 获取一页职称的数据
  const getJobsDataPage = function (nowpage, pagesize) {
    let xhr = null;
    if (window.XMLHttpRequest) {//非IE
      xhr = new XMLHttpRequest()
    } else { // IE
      xhr = new ActiveObject('Microsoft.XMLHTTP')
    }

    xhr.open('get', "/getJobsPage?nowpage=" + nowpage + "&pagesize=" + pagesize, true);
    xhr.send(null)

    // 等待后台回复数据得事件监听
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        let text = xhr.responseText;
        let res = JSON.parse(text)
        console.log(res); //{code: 200, msg: '查询成功', data: Array(5), count: 12}
        if (res.code === 200) {
          // alert('成功')
          // 更新表格数据, 建议单独写一个函数。
          let jobTable = document.querySelector("#jobTable")
          jobTable.innerHTML = ""
          let strHtml = '';
          res.data.forEach((el, index) => {
            strHtml += `<tr>
                <td>${index + 1}</td>
                <td>${el.jname}</td>
                <td>${el.jdes}</td>
                <td>
                  <button type="button" class="btn btn-warning btn-edit" data-id="${el.jid}">修改</button>
                  <button type="button" class="btn btn-danger btn-delete" data-id="${el.jid}">删除</button>
                </td>
              </tr>`;
          });
          jobTable.innerHTML = strHtml;

          // 创建分页：
          // if (res.count > pagesize) {
          $("#myPage").show();

          // 循环渲染条数的下拉列表
          $("#page").html('');
          let optionsHtml = '';
          pageSizes.forEach(el => {
            optionsHtml += ` <option value="${el}">${el}</option>`;
          })
          $("#page").html(optionsHtml);
          $("#page").val(pagesize) //设置下拉列表默认选择的项目

          // 表示不止一页数据，大于就创建
          total = Math.ceil(res.count / pagesize);
          $(".pagination").html('');
          let strHtml2 = '';
          for (let i = 1; i <= total; i++) {
            strHtml2 += `<li class="page-item ${nowpage === i ? 'active' : ''}" aria-current="page">
                <span class="page-link">${i}</span>
              </li>`;
          }
          $(".pagination").html(strHtml2);

          // } else {
          //   $("#myPage").hide()
          // }


        } else {
          // alert('失败')
        }
      }
    }
  }

  // 分页页码的事件委托
  document.getElementsByClassName('pagination')[0].onclick = function (event) {
    let tagName = event.target.tagName;
    console.log(tagName)
    if (tagName === 'SPAN') {
      nowpage = Number(event.target.innerText);
      // 获取到页码，调用查询一页数据的函数
      getJobsDataPage(nowpage, pagesize)
    }
  }

  // 给分页的下拉列表绑定事件;
  $("#page").on('change', function () {
    let pagesize = Number($(this).val())
    console.log(pagesize);
    nowpage = 1;
    getJobsDataPage(nowpage, pagesize)
  })

  // 获取所有的职称数据
  const getJobsData = function () {
    // 1.创建ajax核心对象
    // console.log(window.XMLHttpRequest)
    let xhr;
    if (window.XMLHttpRequest) {//非IE
      xhr = new XMLHttpRequest()
    } else { // IE
      xhr = new ActiveObject('Microsoft.XMLHTTP')
    }
    // 配置对象：
    // xhr.open('get|post', url?key=value, 同步|异步)
    xhr.open('get', "/getJobs", true);
    xhr.send(null)  // get请求时，参数不写在send()中，而是再url?key=V;

    // 等待后台回复数据得事件监听
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log('请求成功')
        let textData = xhr.responseText; // 获取后端得响应数据，数据是字符串。
        // console.log(textData) // JSON字符串， 需要转换程json对象格式。

        let result = JSON.parse(textData)
        console.log(result)

        if (result.code === 200) {
          // alert(result.msg);
          // 更新表格
          let jobTable = document.querySelector("#jobTable")
          jobTable.innerHTML = ""
          let strHtml = '';
          result.data.forEach((el, index) => {
            strHtml += `<tr>
                <td>${index + 1}</td>
                <td>${el.jname}</td>
                <td>${el.jdes}</td>
                <td>
                  <button type="button" class="btn btn-warning btn-edit" data-id="${el.jid}">修改</button>
                  <button type="button" class="btn btn-danger btn-delete" data-id="${el.jid}">删除</button>
                </td>
              </tr>`;
          });
          jobTable.innerHTML = strHtml;
        } else {
          alert(result.msg);
        }
      }
    }
  }

  // 事件委托：
  document.getElementById('jobTable').onclick = function (event) {
    // console.log(event.target)
    let jid = event.target.getAttribute('data-id')
    if (event.target.className.includes('btn-edit')) {
      // alert('点击编辑')
      editJobsHandler(jid)
    } else if (event.target.className.includes('btn-delete')) {
      // alert('点击删除')

      deleteJobsHandler(jid);
    }
  }

  // 添加职称显示modal
  $('#addJobBtn').on('click', function () {
    $("#addJobModal").modal('show')
  })

  // 保存添加得职称数据
  $('.btn-add').on('click', function () {
    let jobname = $("#jobname").val();
    let jobdes = $("#jobdes").val();

    // 省略正则验证。。。，如果验证通过，就发起AJAX请求
    let xhr = null;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    xhr.open('get', `/addJobs?jobname=${jobname}&jobdes=${jobdes}`, true);
    xhr.send()
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        let text = xhr.responseText;
        let res = JSON.parse(text)
        console.log(res)
        if (res.code === 200) {
          // alert('添加成功')
          $("#addJobModal").modal('hide')
          getJobsData(); //重修调用接口，动态渲染表格
        } else {
          alert('添加失败')
        }
      }
    }

  });

  // 删除职称
  const deleteJobsHandler = function (jid) {
    console.log(jid)

    // ajax post:
    let xhr = null;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    /* post时，url不拼接参数，send()里面放参数 ，
    必须写请求头信息。 xhr.setRequestHeader（）；
    */
    xhr.open('post', '/deleteJobs', true)
    // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded") // 设置请求头为普通的表单提交数据的编码格式。
    // xhr.send(`jid=${jid}`);
    // 如果参数很多个，可以传json对象，
    xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8")
    // 必须把对象转为json字符串，后端才能拿到参数。
    xhr.send(JSON.stringify({ 'jid': jid }))

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        let text = xhr.responseText;
        let res = JSON.parse(text)
        console.log(res)
        if (res.code === 200) {
          // alert('删除成功')
          getJobsData(); //重修调用接口，动态渲染表格
        } else {
          alert('添加失败')
        }
      }
    }

  }

  // 修改职称
  const editJobsHandler = (jid) => {
    console.log(jid)
    let xhr = null;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }

    xhr.open('post', '/getJobInfo', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    xhr.send('jid=' + jid);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        let text = xhr.responseText;
        let resData = JSON.parse(text)
        console.log(resData)
        if (resData.code === 200) {
          $("#editJobModal").modal('show')
          // 更新表单的值
          let obj = resData.data[0] // {jid: 4, jname: '主任医生', jdes: '主任医生，20年工作经验。'}
          $("#jid").val(obj.jid)
          $("#jobname2").val(obj.jname)
          $("#jobdes2").val(obj.jdes)

        } else {
          alert('请求数据失败')
        }
      }
    }
  }


  // 保存修改的事件绑定：
  $(".btn-edit").on('click', function () {
    let jid = $("#jid").val()
    let jname = $("#jobname2").val();
    let jdes = $("#jobdes2").val();

    let flag = true;

    if (!/^.{1,20}$/.test(jname)) {
      flag = false;
      $("#jobnamehelp2").text('请正确输入医生职称')
    } else {
      $("#jobnamehelp2").text('验证成功')
      $("#jobnamehelp2").css('color', 'green!important')
    }
    if (!/^.{1,50}$/.test(jdes)) {
      flag = false;
      $("#jobdeshelp2").text('请正确输入医生职称的描述')
      $("#jobdeshelp2").removeClass('text-muted')
      $("#jobdeshelp2").removeClass('text-success')
      $("#jobdeshelp2").addClass('text-danger')
    } else {
      $("#jobdeshelp2").text('验证成功')
      $("#jobdeshelp2").removeClass('text-muted')
      $("#jobdeshelp2").removeClass('text-danger')
      $("#jobdeshelp2").addClass('text-success')
    }

    if (flag === false) {
      return;
    }

    let xhr = null;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }

    xhr.open('post', '/updateJobInfo', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    xhr.send(`jid=${jid}&jname=${jname}&jdes=${jdes}`);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        let text = xhr.responseText;
        let res = JSON.parse(text)
        if (res.code === 200) {
          console.log('修改成功')

          getJobsData(); //重修调用接口，动态渲染表格
        } else {
          alert('修改失败')
        }
        $("#editJobModal").modal('hide')
      }
    }


  })
</script>

</html>